<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\View;
use App\Core\CSRF;
use App\Core\Flash;
use App\Services\Auth;
use App\Services\Statistics;
use App\Services\BackupService;
use App\Services\SettingsService;
use App\Services\Database;
use App\Services\ThemeManager;
use PDO;

final class AdminController
{
    private function requireLogin(string $intendedUrl = '/admin'): bool
    {
        if (!Auth::check()) {
            $_SESSION['intended_url'] = $intendedUrl;
            header('Location: /login');
            exit;
        }
        return true;
    }

    public function dashboard(): string
    {
        if (!$this->requireLogin('/admin')) {
            return '';
        }

        $stats = Statistics::getDashboardStats();
        $logStats = Statistics::getLogStats();
        $recentActivity = Statistics::getRecentActivity();

        return View::render('admin/dashboard', [
            'title' => '管理面板',
            'stats' => $stats,
            'logStats' => $logStats,
            'recentActivity' => $recentActivity,
            'layout' => 'admin'
        ]);
    }

    public function logs(): string
    {
        if (!$this->requireLogin('/admin/logs')) {
            return '';
        }

        $logType = $_GET['type'] ?? 'access';
        $lines = intval($_GET['lines'] ?? 50);

        $logFile = '';
        switch ($logType) {
            case 'access':
                $logFile = APP_ROOT . '/storage/logs/access.log';
                break;
            case 'app':
                $logFile = APP_ROOT . '/storage/logs/app.log';
                break;
            case 'rate_limit':
                $logFile = APP_ROOT . '/storage/logs/rate_limit.json';
                break;
        }

        $logContent = '';
        if (file_exists($logFile)) {
            if ($logType === 'rate_limit') {
                $logContent = file_get_contents($logFile);
                $logContent = json_encode(json_decode($logContent, true), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            } else {
                $logLines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                if ($logLines) {
                    $logLines = array_slice($logLines, -$lines);
                    $logContent = implode("\n", array_reverse($logLines));
                }
            }
        }

        return View::render('admin/logs', [
            'title' => '系统日志',
            'logType' => $logType,
            'logContent' => $logContent,
            'lines' => $lines,
            'layout' => 'admin'
        ]);
    }

    public function clearLogs(): string
    {
        if (!$this->requireLogin('/admin/logs')) {
            return '';
        }

        CSRF::validateOrAbort();

        $logType = $_POST['type'] ?? '';
        $success = false;

        switch ($logType) {
            case 'access':
                $success = @file_put_contents(APP_ROOT . '/storage/logs/access.log', '');
                break;
            case 'app':
                $success = @file_put_contents(APP_ROOT . '/storage/logs/app.log', '');
                break;
            case 'rate_limit':
                $success = @file_put_contents(APP_ROOT . '/storage/logs/rate_limit.json', '{}');
                break;
        }

        if ($success !== false) {
            Flash::success('日志已清空');
        } else {
            Flash::error('清空日志失败');
        }

        header('Location: /admin/logs?type=' . $logType);
        exit;
    }

    public function backup(): string
    {
        if (!$this->requireLogin('/admin/backup')) {
            return '';
        }

        $backups = BackupService::getBackupList();

        return View::render('admin/backup', [
            'title' => '数据备份',
            'backups' => $backups,
            'layout' => 'admin'
        ]);
    }

    public function createBackup(): string
    {
        if (!$this->requireLogin('/admin/backup')) {
            return '';
        }

        CSRF::validateOrAbort();

        $result = BackupService::createDatabaseBackup();

        if ($result['success']) {
            Flash::success($result['message'] . ' - ' . $result['filename']);
        } else {
            Flash::error($result['message']);
        }

        header('Location: /admin/backup');
        exit;
    }

    public function downloadBackup(): string
    {
        if (!$this->requireLogin('/admin/backup')) {
            return '';
        }

        $filename = $_GET['file'] ?? '';
        BackupService::downloadBackup($filename);
        return '';
    }

    public function deleteBackup(): string
    {
        if (!$this->requireLogin('/admin/backup')) {
            return '';
        }

        CSRF::validateOrAbort();

        $filename = $_POST['filename'] ?? '';

        if (BackupService::deleteBackup($filename)) {
            Flash::success('备份文件已删除');
        } else {
            Flash::error('删除备份文件失败');
        }

        header('Location: /admin/backup');
        exit;
    }

    public function settings(): string
    {
        if (!$this->requireLogin('/admin/settings')) {
            return '';
        }

        // 初始化默认设置
        SettingsService::initializeDefaults();

        $settings = SettingsService::getAll();
        $defaults = SettingsService::getDefaults();

        return View::render('admin/settings', [
            'title' => '系统设置',
            'settings' => $settings,
            'defaults' => $defaults,
            'layout' => 'admin'
        ]);
    }

    public function updateSettings(): string
    {
        if (!$this->requireLogin('/admin/settings')) {
            return '';
        }

        CSRF::validateOrAbort();

        $allowedSettings = [
            'site_name',
            'site_description',
            'posts_per_page',
            'allow_registration',
            'maintenance_mode',
            'admin_email',
            'timezone'
        ];

        $success = true;
        $updated = 0;

        foreach ($allowedSettings as $key) {
            if (isset($_POST[$key])) {
                $value = $_POST[$key];

                // 特殊处理
                if ($key === 'posts_per_page') {
                    $value = max(1, min(50, intval($value))); // 限制在 1-50 之间
                } elseif ($key === 'allow_registration' || $key === 'maintenance_mode') {
                    $value = isset($_POST[$key]) && $_POST[$key] === '1';
                } else {
                    $value = trim($value);
                }

                if (SettingsService::set($key, $value)) {
                    $updated++;
                } else {
                    $success = false;
                }
            }
        }

        if ($success && $updated > 0) {
            Flash::success("成功更新了 {$updated} 项设置");
        } elseif ($updated === 0) {
            Flash::info('没有设置需要更新');
        } else {
            Flash::error('部分设置更新失败，请检查日志');
        }

        header('Location: /admin/settings');
        exit;
    }

    // 文章管理功能
    public function posts(): string
    {
        if (!$this->requireLogin('/admin/posts')) {
            return '';
        }

        $pdo = Database::pdo();

        $kw = trim((string)($_GET['kw'] ?? ''));
        $page = (int)($_GET['page'] ?? 1);
        if ($page < 1) {
            $page = 1;
        }
        $perPage = 20; // 后台每页显示更多文章
        $offset = ($page - 1) * $perPage;

        $where = '';
        $params = [];
        if ($kw !== '') {
            $where = 'WHERE title LIKE :kw1 OR content LIKE :kw2';
            $params[':kw1'] = '%' . $kw . '%';
            $params[':kw2'] = '%' . $kw . '%';
        }

        // 统计总数
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM posts {$where}");
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v, PDO::PARAM_STR);
        }
        $stmt->execute();
        $total = (int) $stmt->fetchColumn();

        // 查询列表
        $sql = "SELECT id, title, created_at, updated_at FROM posts {$where} ORDER BY created_at DESC LIMIT {$perPage} OFFSET {$offset}";
        $stmt = $pdo->prepare($sql);
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v, PDO::PARAM_STR);
        }
        $stmt->execute();
        $posts = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        $totalPages = max(1, (int) ceil($total / $perPage));

        return View::render('admin/posts', [
            'title' => '文章管理',
            'posts' => $posts,
            'kw' => $kw,
            'page' => $page,
            'totalPages' => $totalPages,
            'total' => $total,
            'layout' => 'admin'
        ]);
    }

    // 用户管理功能
    public function users(): string
    {
        if (!$this->requireLogin('/admin/users')) {
            return '';
        }

        $pdo = Database::pdo();

        $kw = trim((string)($_GET['kw'] ?? ''));
        $page = (int)($_GET['page'] ?? 1);
        if ($page < 1) {
            $page = 1;
        }
        $perPage = 20;
        $offset = ($page - 1) * $perPage;

        $where = '';
        $params = [];
        if ($kw !== '') {
            $where = 'WHERE username LIKE :kw1 OR email LIKE :kw2';
            $params[':kw1'] = '%' . $kw . '%';
            $params[':kw2'] = '%' . $kw . '%';
        }

        // 统计总数
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users {$where}");
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v, PDO::PARAM_STR);
        }
        $stmt->execute();
        $total = (int) $stmt->fetchColumn();

        // 查询列表
        $sql = "SELECT id, username, email, created_at FROM users {$where} ORDER BY created_at DESC LIMIT {$perPage} OFFSET {$offset}";
        $stmt = $pdo->prepare($sql);
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v, PDO::PARAM_STR);
        }
        $stmt->execute();
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        $totalPages = max(1, (int) ceil($total / $perPage));

        return View::render('admin/users', [
            'title' => '用户管理',
            'users' => $users,
            'kw' => $kw,
            'page' => $page,
            'totalPages' => $totalPages,
            'total' => $total,
            'layout' => 'admin'
        ]);
    }

    /**
     * 显示主题管理页面
     */
    public function themes(): string
    {
        if (!$this->requireLogin('/admin/themes')) {
            return '';
        }

        $themeManager = ThemeManager::getInstance();
        $themes = $themeManager->getAvailableThemes();
        $currentTheme = $themeManager->getCurrentTheme();

        $themeData = [];
        foreach ($themes as $theme) {
            $themeData[$theme] = $themeManager->getThemeConfig($theme);
        }

        return View::render('admin/themes', [
            'title' => '主题管理',
            'themes' => $themeData,
            'currentTheme' => $currentTheme,
            'layout' => 'admin'
        ]);
    }

    /**
     * 激活主题
     */
    public function activateTheme(): string
    {
        if (!$this->requireLogin('/admin/themes')) {
            return '';
        }

        CSRF::validateOrAbort();

        $theme = $_POST['theme'] ?? 'default';

        try {
            $themeManager = ThemeManager::getInstance();
            $themeManager->setCurrentTheme($theme);

            Flash::success("主题 '{$theme}' 已成功激活");
        } catch (\Exception $e) {
            Flash::error("激活主题失败: " . $e->getMessage());
        }

        header('Location: /admin/themes');
        exit;

        return '';
    }
}
